﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MedicineTracker.Model;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace MedicineTracker.ViewModel
{
    public class PurchasesViewModel : Database, INotifyPropertyChanged
    {
        private ObservableCollection<Purchase> _purchases;

        public ObservableCollection<Purchase> Purchases
        {
            get { return _purchases; }
        }

        public PurchasesViewModel()
        {
            _purchases = new ObservableCollection<Purchase>();
            using (Connection)
            {
                try
                {
                    Connection.Open();
                    Command.CommandText = "SELECT pur.id, pur.medicine_id AS med_id, pur.supplier AS sup_id, pur.purchase_date, pur.expiry_date, pur.qty, pur.qty_left, pur.batch_no, med.name AS med, sup.name AS supplier FROM purchases pur INNER JOIN medicines med ON med.id = pur.medicine_id INNER JOIN suppliers sup ON sup.id = pur.supplier";
                    Command.Connection = Connection;
                    DataReader = Command.ExecuteReader();
                    while (DataReader.Read())
                    {
                        _purchases.Add(new Purchase
                        {
                            ID = Convert.ToInt32(DataReader["id"]),
                            BatchNo = (string)DataReader["batch_no"],
                            ExpiryDate = (DateTime)DataReader["expiry_date"],
                            MedicineID = Convert.ToInt32(DataReader["med_id"]),
                            Medicine = (string)DataReader["med"],
                            PurchaseDate = (DateTime)DataReader["purchase_date"],
                            Qty = Convert.ToInt32(DataReader["qty"]),
                            QtyLeft = Convert.ToInt32(DataReader["qty_left"]),
                            Supplier = (string)DataReader["supplier"],
                            SupplierID = Convert.ToInt32(DataReader["sup_id"])
                        });
                    }
                }
                catch
                {
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
